package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VideoService {
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference(version = "1.0.0",check = false)
    private VideoApi videoApi;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0",check = false)
    private QuanZiApi quanZiApi;
    @Autowired
    private QuanZiService quanZiService;
    @Autowired
    private VideoMQService videoMQService;

    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();
        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);
        try {
            /*PicUploadResult uploadResult = this.picUploadService.upload(picFile);*/
            video.setPicUrl("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/photo/11/1.jpg");
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream()
                    , videoFile.getSize(), StrUtil.subAfter(videoFile.getOriginalFilename(), '.', true),
                    null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
             String videoId=videoApi.saveVideo(video);
            if(StrUtil.isNotEmpty(videoId)){
                videoMQService.videoMsg(videoId);
            }
             return StrUtil.isNotEmpty(videoId);
        } catch (Exception e) {
            log.error("上传小视频出错userId="+user.getId()+", file = " + videoFile.getOriginalFilename(), e);
        }return null;
    }

    public PageResult queryVideoList(Integer page, Integer pagesize) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        PageInfo<Video> pageInfo = videoApi.queryVideoList(user.getId(), page, pagesize);
        List<Video> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video record : records) {
            // 拼凑VO对象
            VideoVo videoVo = new VideoVo();

            videoVo.setUserId(record.getUserId());
            videoVo.setCover(record.getPicUrl());
            videoVo.setVideoUrl(record.getVideoUrl());
            videoVo.setId(record.getId().toHexString());
            videoVo.setSignature("我就是我~"); // 签名

            videoVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(videoVo.getId())));
            videoVo.setHasFocus(videoApi.isFollowUser(user.getId(), videoVo.getUserId()) ? 1 : 0);
            videoVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(), videoVo.getId()) ? 1 : 0);
            videoVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(videoVo.getId())));
            for (UserInfo userInfo : userInfos) {
                if(ObjectUtil.equals(videoVo.getUserId(),userInfo.getUserId())){
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            } videoVoList.add(videoVo);
            }pageResult.setItems(videoVoList);
             return pageResult;
    }

    public Long likeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.likeComment(user.getId(), videoId);
        if(result){
            videoMQService.likeVideoMsg(videoId);
            Long likeCount = quanZiApi.queryLikeCount(videoId);
            return likeCount;
        }return null;
    }

    public Long dislikeComment(String videoId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLikeComment(user.getId(), videoId);
        if(result){
            videoMQService.disLikeVideoMsg(videoId);
            Long likeCount = quanZiApi.queryLikeCount(videoId);
            return likeCount;
        }return null;
    }

    public PageResult queryCommentsList(String videoId, Integer page, Integer pagesize) {
        if(!videoId.matches("(?i)^((0x)?([a-f\\d])+,\\s)*(0x)?([a-f\\d])+$")){
            if(ObjectUtil.isAllNotEmpty(videoId,page,pagesize)){
                return quanZiService.queryCommentlist(videoId, page,pagesize);
            }
        }return null;
    }

    public Boolean saveComment(String content, String videoId) {
        Boolean result = this.quanZiService.saveComments(videoId, content);
        if(result){
            videoMQService.commentVideoMsg(videoId);
        }
        return result;
    }

    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
       return videoApi.followUser(user.getId(),userId);
    }

    public Boolean disfollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return videoApi.disFollowUser(user.getId(),userId);
    }
}
